package com.sesxh.zbss.service.impl;

import java.util.Map;
import java.util.Set;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.sesxh.zbss.cache.TableCache;
import com.sesxh.zbss.mapper.TableMapper;
import com.sesxh.zbss.service.TableService;
@Service("com.sesxh.zbss.service.impl.TableServiceImpl")
public class TableServiceImpl implements TableService {
	@Autowired
	private TableMapper tableMapper;
	@Override
	public void createTableOrAddCol(String tableName, Map<String, Object> colmap) {
		 boolean ishaveTable = TableCache.isHaveTable(tableName);
		 String colSql = null;
		  if (!ishaveTable) {
			  int result = tableMapper.existTable(tableName);
			  if (result == 0) {
				  String tablesql = tableSql(tableName,colmap);
				  tableMapper.createNewTable(tablesql);
				  TableCache.addTaleName(tableName);
				  TableCache.addCol(tableName, colmap.keySet());
			  }
			  
		  }else {
			 Set<String> notHaveCol = TableCache.notHaveCol(tableName, colmap.keySet());
			 if (notHaveCol != null && notHaveCol.size() != 0) {
				 colSql = addColSql(tableName,colmap,notHaveCol);
				 tableMapper.addCols(colSql);
				 TableCache.addCol(tableName, notHaveCol);
			 }
		  }
	}
	
	
	private String tableSql(String tablename,Map<String,Object> col) {
		  StringBuilder sql  = new StringBuilder();
		  sql.append("    CREATE TABLE IF NOT EXISTS `").append(tablename).append("` (");
		  sql.append("           `id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT 'ID',");
		  sql.append("           `appId` bigint(20) NOT NULL COMMENT '所属应用',");
		  sql.append("           `tenantId` bigint(20) NOT NULL COMMENT '所属租户',");
		  for(Map.Entry<String, Object> entry : col.entrySet()){
			    String mapKey = entry.getKey();
			    sql.append("`").append(mapKey).append("` varchar(100) DEFAULT NULL,");
			}
		  sql.append("  PRIMARY KEY (`id`) USING BTREE ");
		  sql.append(") ENGINE=InnoDB AUTO_INCREMENT=13 DEFAULT CHARSET=utf8 ROW_FORMAT=DYNAMIC;");
		  return sql.toString();
	  }
	  
	  private String addColSql(String tablename,Map<String,Object> col,Set<String> notHaveCols) {
		  StringBuilder sql  = new StringBuilder();
		  sql.append("    ALTER TABLE ").append("`").append(tablename).append("`");
		  for(String notHaveCol:notHaveCols){
			  sql.append("    ADD COLUMN `").append(notHaveCol).append("` varchar(100) DEFAULT NULL,");
			}
		  
		  sql.append("   ALGORITHM=INPLACE, LOCK=NONE");
		  return sql.toString();
	  }
	  

}
